<template>
  <div>
    <div v-if="placeholder" style="font-size: 0.9rem;margin: 2px">{{ placeholder }}</div>
    <van-uploader
      v-model="fileList"
      multiple
      :after-read="doUpload"
      :before-delete="deleteFile"
      @click-preview="viewFile"
      :accept="uploadAccept">
    </van-uploader>
  </div>
</template>

<script>
  import { postAction,getFileAccessHttpUrl } from '@/api'
  import { downloadAbled } from '@/util/util'

  export default {
    name: 'AppUploader',
    props:{
      biz:{
        type:String,
        default:'app',
        required:false
      },
      value:{
        type:String,
        required:false
      },
      placeholder:{
        type:String,
        required:false,
        default:''
      },
      type:{
          type:String,
          required:false,
          default:'image'
      }

    },
    watch:{
      value:{
        immediate:true,
        handler(val){
          this.initFileList(val)
        }
      }
    },
    model: {
      prop: 'value',
      event: 'input'
    },
    computed:{
      uploadAccept(){
        if(this.type==='image'){
            return 'image/*'
        }else{
            return '*'
        }
      }
    },
    data(){
      return {
        // {url:''} {content:'base64',file:'file对象'}
        fileList:[],
        uploadUrl:window._CONFIG['domainURL']+"/sys/common/upload",

        innerList:[]
      }
    },
    methods:{
      getNewPath(path){
        if(!path){
          path = ''
        }
        if(!this.value){
          return path
        }else{
          return this.value+","+path
        }
      },
      addInnerObj(file,url){
        this.innerList.push({
          fileName:file.name,
          filePath:url,
          fileSize:file.size
        })
      },
      deleteInnerObj(url){
        this.innerList = this.innerList.filter(item=>{
          return url!=item.filePath
        })
      },
      doUpload(obj){
        let formData = new FormData();
        formData.append("file",obj.file,obj.file.name)
        formData.append("bizPath",this.biz)
        postAction(this.uploadUrl,formData).then(res=>{
          console.log("res",res);
          if(res.success){
            this.addInnerObj(obj.file,res.message)
            this.$emit('input',this.getNewPath(res.message))
          }else{
            this.$toast('文件上传失败,请联系管理员')
            this.fileList.pop()
          }
        })
      },
      notImg(path){
        let arr = ['txt','doc','pdf','docx','ppt','pptx','xls','xlsx']
        let r = false
        for(let a of arr){
          if(path.endsWith(a)){
            r = true
            break;
          }
        }
        return r;
      },
      deleteFile(obj){
        console.log("obj",obj)
        console.log("this.value",this.value)
        let arr = this.value.split(",")
        let newPath = arr.filter(item=>{
          let a = obj.url.indexOf(item)<0 && item.indexOf(obj.url)<0
          if(!a){
            this.deleteInnerObj(item)
          }
          return a;
        }).join(",")
        this.$emit('input',newPath)
        return true
      },
      initFileList(paths){
        if(!paths || paths.length==0){
          this.fileList = [];
          this.innerList = []
          return;
        }
        let fileList=[]
        let arr = paths.split(",")
        for(var a=0;a<arr.length;a++){
          if(this.notImg(arr[a])){
            fileList.push({
              type:'file',
              url:arr[a].substring(arr[a].lastIndexOf("/")+1)
            })
          }else{
            fileList.push({
              url:getFileAccessHttpUrl(arr[a])
            })
          }

        }
        this.fileList = [...fileList]
      },

      getNeedJsonStr(){
        return JSON.stringify(this.innerList)
      },
      viewFile(obj){
        if(obj.type==='file'){
          let url = getFileAccessHttpUrl(obj.url);
          downloadAbled(url).then(()=>{
            location.href = url;
          }).catch(()=>{
            this.$toast('文件识别失败!')
          })
        }
        return true;
      }
    }
  }
</script>

<style scoped>

</style>